package edu.maine.usm.server;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.motechproject.mrs.model.MRSEncounter;
import org.motechproject.mrs.model.MRSObservation;
import org.motechproject.mrs.model.MRSPatient;
import org.motechproject.openmrs.advice.ApiSession;
import org.motechproject.openmrs.advice.LoginAsAdmin;
import org.motechproject.openmrs.services.OpenMRSEncounterAdapter;
import org.motechproject.openmrs.services.OpenMRSPatientAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import edu.maine.usm.dto.PatientDTO;
import edu.maine.usm.rpc.OpenMRSClientService;

@Component
public class OpenMRSClientServiceImpl implements OpenMRSClientService {
	
	Logger logger = LoggerFactory.getLogger(OpenMRSClientServiceImpl.class);
	private OpenMRSEncounterAdapter encounteredAdapter;
	private OpenMRSPatientAdapter patientAdapter;

	@Autowired
	public OpenMRSClientServiceImpl(OpenMRSEncounterAdapter encounterAdapter, OpenMRSPatientAdapter patientAdapter) {
		this.encounteredAdapter = encounterAdapter;
		this.patientAdapter = patientAdapter;
	}
	
	public boolean hasConcept(String patientId, String conceptName) {
		MRSEncounter encounter = encounteredAdapter.getLatestEncounterByPatientMotechId(patientId, "ADULTINITIAL");
		Set<MRSObservation> observations = encounter.getObservations();
		boolean found = false;
		for(MRSObservation obs : observations) {
			if (obs.getConceptName().equals(conceptName)) {
				found =  true;
			}
		}
		
		logger.warn("Found:" + found);
		return found;
	}

	@LoginAsAdmin
	@ApiSession
	public ArrayList<PatientDTO> searchPatient(String name) {
		hasConcept("DOE-1", "Demo Vaccination 1");
		List<MRSPatient> patients = patientAdapter.search(name, null);
		ArrayList<PatientDTO> dtos = new ArrayList<PatientDTO>();
		
		for(MRSPatient patient : patients) {
			PatientDTO dto = new PatientDTO();
			dto.setFirstName(patient.getPerson().getFirstName());
			dto.setLastName(patient.getPerson().getLastName());
			dto.setMotechIdentifier(patient.getMotechId());
			dtos.add(dto);
		}
		
		return dtos;
	}

}
